package conn

import (
	"easyreport/conf"
	"fmt"
	"github.com/go-xorm/xorm"
	"time"
)

var DB = make(map[string]*xorm.Engine)

func NewDB() {
	for k, v := range conf.Conf.Pool {
		db, err := xorm.NewEngine(v["dialect"].(string), v["url"].(string))
		if err != nil {
			fmt.Println(err)
			CloseDB()
			panic("数据库初始化失败！")
			return
		}
		db.ShowSQL(conf.Get().ShowSql)
		db.SetMaxIdleConns(v["maxidle"].(int))
		db.SetMaxOpenConns(v["maxopen"].(int))
		err = db.Ping()
		if err != nil {
			fmt.Println(err)
			CloseDB()
			panic("数据库初始化失败！")
			return
		}
		go func() {
			for range time.Tick(time.Minute * 5) {
				db.Query("SELECT 1 FROM DUAL")
			}
		}()
		DB[k] = db
	}
}

func CloseDB() {
	for _, v := range DB {
		v.Clone()
	}
}
